﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="CommandBindingCollection.cs" company="JDML Consulting Ltd.">
//   Copyright 2011 Photon Project - http://photon.codeplex.com
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace Photon.Windows.Input.Commands
{
    using System;
    using System.Collections.ObjectModel;
    using System.Linq;
    using System.Windows.Input;

    public class CommandBindingCollection : Collection<CommandBinding>
    {
        #region Fields

        private int _updateCount;

        #endregion

        protected override void ClearItems()
        {
            base.ClearItems();
            Changed();
        }

        protected override void InsertItem(int index, CommandBinding item)
        {
            base.InsertItem(index, item);
            Changed();
        }

        protected override void RemoveItem(int index)
        {
            base.RemoveItem(index);
            Changed();
        }

        protected override void SetItem(int index, CommandBinding item)
        {
            base.SetItem(index, item);
            Changed();
        }

        public CommandBinding FindMatch(ICommand command)
        {
            return this.FirstOrDefault(x => x.Command == command);
        }

        public int BeginUpdate()
        {
            return ++_updateCount;
        }

        public void EndUpdate()
        {
            if (_updateCount == 0)
            {
                throw new InvalidOperationException("No corresponding end update.");
            }

            _updateCount--;
            Changed();
        }

        private void Changed()
        {
            if (_updateCount == 0)
            {
                CommandManager.InvalidateRequerySuggested();
            }
        }
    }
}